package com.framework.base.filters;

import java.io.IOException;
import java.util.StringTokenizer;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

/**
 * Title: IP过滤器</p>
 * Description: 现在非指定IP的用户访问系统</p>
 * @author www.51wuxia.com
 * @version 1.0
 */
public class IPFilter implements Filter {
    @SuppressWarnings("unused")
	private FilterConfig config;
    private static String IP_ACCESS = ""; //可以访问应用的IP地址
    private String[] total_IP = null;

    public IPFilter() {
    }

    /**
     * 初始化
     * @param filterConfig FilterConfig
     * @throws ServletException
     */
    public void init(FilterConfig filterConfig) throws ServletException {
        this.config = filterConfig;
        IP_ACCESS = filterConfig.getInitParameter("IP_ACCESS");
        if (IP_ACCESS == null)
            IP_ACCESS = "192.168.0.1-192.168.0.255";
        total_IP = IP_ACCESS.split(","); //能访问应用的IP地址段
    }

    /**
     * IP过滤检测
     * @param request ServletRequest
     * @param response ServletResponse
     * @param chain FilterChain
     * @throws IOException
     * @throws ServletException
     */
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException,
            ServletException {
        boolean access = false; //访问权限
        String IP = request.getRemoteAddr(); //访问者IP
        if (IP.equals("127.0.0.1")) access = true;  //本机可以访问

        StringTokenizer toke = new StringTokenizer(IP, ".");
        int dots = 0;
        String byte1 = "";
        String byte2 = "";
        String byte3 = "";
        int byte4 = 0;
        String client = "";
        while (toke.hasMoreTokens()) {
            ++dots;
            if (dots == 1) {
                byte1 = toke.nextToken();
            } else if (dots == 2) {
                byte2 = toke.nextToken();
            } else if (dots == 3) {
                byte3 = toke.nextToken();
            } else if (dots == 4) {
                byte4 = Integer.parseInt(toke.nextToken());
            }
        }
        client = byte1 + "." + byte2 + "." + byte3; //访问者IP的前三位

        for (int i = 0; i < total_IP.length; i++) {
            if (access)break;
            String[] single_IP = total_IP[i].split("-");
            int min = 0;
            int max = 0;
            for (int j = 0; j < single_IP.length; j++) {
                if (access)break;
                if (j == 0)
                    min = Integer.parseInt(single_IP[j].substring(single_IP[j].
                            lastIndexOf(".") + 1));
                else if (j == 1) {
                    max = Integer.parseInt(single_IP[j].substring(single_IP[j].
                            lastIndexOf(".") + 1));
                    if (single_IP[j].indexOf(client) > -1) {
                        if (byte4 >= min && byte4 <= max) {
                            access = true;
                        }
                    }
                }
            }
        }

        HttpServletResponse httpResp = null;
        if (response instanceof HttpServletResponse)
            httpResp = (HttpServletResponse) response;

        if (access) {
            chain.doFilter(request, response);
        } else {
            httpResp.sendError(HttpServletResponse.SC_FORBIDDEN,
                               "您的IP已经被限制访问！！！");
        }

    } // doFilter

    public void destroy() {
        /*
         * called before the Filter instance is removed from service by the web
         * container
         */
    }

}

